package com.cmc6.websocket.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.cmc6.common.model.enums.SocketMessageEnum;
import com.cmc6.websocket.constant.CommonConstant;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通道组池，管理所有websocket连接
 */
public class MyChannelHandlerPool {

    public static AttributeKey<Long> USER_ID_KEY = AttributeKey.valueOf("userId");
    // socket连接记录的 主键id
    public static AttributeKey<Long> SOCKET_ID_KEY = AttributeKey.valueOf(CommonConstant.SOCKET_ID);

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 根据 key 查找 channel
     */
    public static List<Channel> getChannelByIdSet(AttributeKey<Long> key, Set<Number> idSet) {
        if (CollUtil.isEmpty(idSet)) {
            return new ArrayList<>(); // 防止空指针
        }
        Set<Long> idLongSet = idSet.stream().map(Convert::toLong).collect(Collectors.toSet());
        return MyChannelHandlerPool.channelGroup.stream().filter(channel -> idLongSet.contains(channel.attr(key).get()))
            .collect(Collectors.toList());
    }

    /**
     * 发送给所有人
     */
    public static void send2All(SocketMessageEnum socketMessageEnum) {
        channelGroup.writeAndFlush(socketMessageEnum.toSocketText());
    }
}


